<?php

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */

    public $stt_link = 1;
    public $layout = 'main';
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
    public function actionHome(){
        $this->stt_link = 1;
        Yii::app()->theme = 'bsthu';
        $this->layout = 'main';

        //Lay danh sach bai viet hien thi trang chu
        $criteria = new CDbCriteria();
        $criteria->alias = 'bv';
        $criteria->addCondition('bv.is_active = 1');
        $criteria->addCondition('dmnhombv.is_active = 1');
        $criteria->addCondition('is_home = 1');
        $criteria->select = 'baiviet.*, dmnhombv.* ';
        $criteria->order = 'dmnhombv.stt ASC, dmnhombv.ten_nhom ASC';
        $criteria->with = 'dmnhombv';
        $dsBaiVietTrangChu = Baiviet::model()->findAll($criteria);

        //Lay bai viet gioi thieu
        $bvGioiThieu = Baiviet::model()->findByAttributes(array('is_active'=>1,'is_about'=>1),array('order'=>' stt ASC'));

        // Lay description, title, keyword trong model config
        $description = Config::GetValue('description');
        $keys = Config::GetValue('keywords');
        $title = Config::GetValue('title');
        $this->metaDescription = strip_tags($description);
        $this->metaKeywords = strip_tags($keys);
        $this->setPageTitle(strip_tags($title));

        //Lay slide anh
        $slide = Slide::model()->findAllByAttributes(array('is_active'=>1),array('order'=>'stt ASC'));

        $this->render('/home/index',array('dsBaiVietTrangChu'=>$dsBaiVietTrangChu,'bvGioiThieu'=>$bvGioiThieu, 'slides'=>$slide));
    }

    public function actionMain_menu()
    {
        $alias  = Yii::app()->request->getParam('alias');
        $menu = Menu::model()->findByAttributes(array('alias'=>$alias));
        if(!isset($menu) || empty($menu))
            throw new CHttpException(404, 'Không tìm thấy trang cần tìm.');

        //Lay title, description, keywords trong model menu
        $this->setPageTitle($menu->meta_title);
        $this->metaDescription = $menu->meta_description;
        $this->metaKeywords = $menu->meta_keywords;

        // Lay action cua menu co dang site/action
        $arrController = explode("/",$menu->controler);
        if($arrController[1] == 'contact')
            $this->contact();
        if($arrController[1] == "news")
            $this->dsBaiViet($menu);
        if($arrController[1] == 'about')
            $this->about($menu);

    }

    private function about($menu)
    {
        Yii::app()->theme = 'bsthu';
        $this->layout = 'main';

        $this->stt_link = $menu->id;// set active cho menu

        $dsNhomInMenu = Nhombaiviet::model()->findAllByAttributes(array('is_active' => 1,'menu_id'=>$menu->id), array('order' => 'stt ASC'));

        $criteria = new CDbCriteria();
        $criteria->alias = 'bv';
        $criteria->with = 'dmnhombv';
        $criteria->addCondition('bv.is_active = 1');
        $criteria->addCondition('bv.is_new = 1');
        $criteria->addCondition('dmnhombv.is_active = 1');
        $arrNhomBV = CHtml::listData($dsNhomInMenu,'id','id');
        $criteria->addInCondition('dmnhombv_id',$arrNhomBV);
        $criteria->order = 'bv.stt ASC, bv.ten_bv ASC';
        $criteria->group = "dmnhombv.id";


        $dsBaiVietInNhom = Baiviet::model()->findAll($criteria);
        /*
         * Seo website
         */
        $this->render('/news/ds-baiviet2',array('dsBaiVietInNhom'=>$dsBaiVietInNhom,'dsNhomInMenu'=>$dsNhomInMenu,'menu'=>$menu));
    }
    private function dsBaiViet($menu)
    {

        Yii::app()->theme = 'bsthu';
        $this->layout = 'main';
        $title = $menu->name;
        $this->stt_link = $menu->id;
        $mNhomBV = Nhombaiviet::model()->findAllByAttributes(array('is_active' => 1,'menu_id'=>$menu->id), array('order' => 'stt ASC'));
        CHtml::listData($mNhomBV,'id','id');
        $arrNhom = CHtml::listData($mNhomBV,'id','id');
        $criteria = new CDbCriteria();
        $criteria->alias = 'bv';
        $criteria->addCondition('bv.is_active = 1');
        $criteria->addCondition('dmnhombv.is_active = 1');
        $criteria->addInCondition('dmnhombv_id',$arrNhom);
        $criteria->addCondition('is_new = 1');

        $criteria->order = 'dmnhombv.stt ASC, dmnhombv.ten_nhom ASC';
        $criteria->with = 'dmnhombv';

        $mdBVs = Baiviet::model()->findAll($criteria);
        $this->render('/news/ds-baiviet',array('mdBVs'=>$mdBVs,'mNhomBV'=>$mNhomBV,'title'=>$title));
    }

    private  function contact()
    {
        $this->stt_link = 4;
        Yii::app()->theme = 'bsthu';
        $this->layout = 'main';

        $model=new ContactForm;
        if(isset($_POST['ContactForm']))
        {
            $model->attributes= $_POST['ContactForm'];
            if($model->validate())
            {
                $contact = new Contact();
                $contact->attributes = $_POST['ContactForm'];
                if($contact->save()){
                $name='=?UTF-8?B?'.base64_encode($model->first_name).'?=';
                $subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';
                $headers="From: $name <{$model->email}>\r\n".
                    "Reply-To: {$model->email}\r\n".
                    "MIME-Version: 1.0\r\n".
                    "Content-Type: text/plain; charset=UTF-8";
                mail(Config::GetValue('email_contact'),$subject,$model->body,$headers);

                Yii::app()->user->setFlash('contact','Cảm ơn bạn đã liên hệ với chúng tôi.<br> Chúng tôi sẽ trả lời bạn sớm nhất có thể.');
                $this->refresh();
                }
            }
        }
        $this->render('/contact/index',array('model'=>$model));
    }
	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'

//        $auth=Yii::app()->authManager;

//        $bizRule='return !Yii::app()->user->isGuest;';
//        $auth->createRole('authenticated', 'authenticated user', $bizRule);
//
//        $bizRule='return Yii::app()->user->isGuest;';
//        $auth->createRole('guest', 'guest user', $bizRule);
//
//        $role = $auth->createRole('admin', 'administrator');
//        $auth->assign('admin',1); // adding admin to first user created
//        $auth->save();

//        $auth=Yii::app()->authManager;
//        $bizRule = 'return Yii::app()->user->id==$params["User"]->id;';
//        $auth->createTask('updateSelf', 'update own information', $bizRule);
//
//        $role = $auth->getAuthItem('authenticated'); // pull up the authenticated role
//        $role->addChild('updateSelf'); // assign updateSelf tasks to authenticated users
		$this->render('index');
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
        Yii::app()->theme = 'bsthu';
        Yii::app()->layout = 'admin';
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}

	/**
	 * Displays the contact page
	 */
//	public function actionContact()
//	{
//		$model=new ContactForm;
//		if(isset($_POST['ContactForm']))
//		{
//			$model->attributes=$_POST['ContactForm'];
//			if($model->validate())
//			{
//				$name='=?UTF-8?B?'.base64_encode($model->name).'?=';
//				$subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';
//				$headers="From: $name <{$model->email}>\r\n".
//					"Reply-To: {$model->email}\r\n".
//					"MIME-Version: 1.0\r\n".
//					"Content-Type: text/plain; charset=UTF-8";
//
//				mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);
//				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
//				$this->refresh();
//			}
//		}
//		$this->render('contact',array('model'=>$model));
//	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login()){
                //$this->redirect(Yii::app()->user->returnUrl);
                $this->redirect(array('user/admin'));
            }

		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
}